import getUserTempId from "@/utils/userTempld"
import { reqLogin,reqUserInfo,reqLogout } from "@/api";
 const state ={
    userTempId:getUserTempId(),
    token:localStorage.getItem("token") ||"",
    userInfo:{
      nickName:"",
    },
 };
 const mutations={
   SET_TOKEN_STATE(state, payload) {
      state.token = payload.token;
    },
    SET_USERINFO_STATE(state, payload) {
      state.userInfo = payload.userInfo;
    },
    RESET_USERINFO_STATE(state){
      state.token="";
      state.userInfo={nickName:""};
      localStorage.removeItem("token")
    }
 };
 const actions = {
   async getToken({ commit },userInfo) {
     try {
       const result = await reqLogin(userInfo);
       localStorage.setItem("token",result.token)
       commit("SET_TOKEN_STATE", { token: result.token });
     } catch (e) {
       return Promise.reject(e);
     }
   },
   async getUserInfo({ commit }) {
    try {
      const result = await reqUserInfo();
      commit("SET_USERINFO_STATE", { userInfo: result });
    } catch (e) {
      return Promise.reject(e.message);
    }
  },
  getReseUser({commit}){
    commit ("RESET_USERINFO_STATE")
  },
  async getLogout({commit}){
    try{
      await reqLogout();
      commit("RESET_USERINFO_STATE");
    }catch(e){
      return Promise.reject(e)
    }
  }
}
 export default {
    namespaced:true,
    state,
    mutations,
    actions,
 }